﻿//[lzh]
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(BoxCollider))]
public class UGUIBoxCollider : MonoBehaviour
{
    RectTransform rectTransform;
    BoxCollider boxCollider;

    private Vector2 rectSize = Vector2.zero;
    private Vector2 rectPivot = Vector2.zero;

    void Awake()
    {
        rectTransform = this.transform as RectTransform;
        boxCollider = this.GetComponent<BoxCollider>();
    }

    void Start()
    {
        InNeedUpdateColliderBox();
        SetColliderBox();
    }

    void Update()
    {
        if (InNeedUpdateColliderBox())
        {
            SetColliderBox();
        }
    }

    void SetColliderBox()
    {
        boxCollider.size = new Vector3(rectSize.x, rectSize.y, 1f);
        boxCollider.center = new Vector3( -(rectPivot.x - 0.5f) * rectSize.x, -(rectPivot.y - 0.5f) * rectSize.y, 0f);
    }

    bool InNeedUpdateColliderBox()
    {
        bool need = false;
        if(rectSize != rectTransform.rect.size)
        {
            need = true;
            rectSize = rectTransform.rect.size;
        }

        if(rectPivot != rectTransform.pivot)
        {
            need = true;
            rectPivot = rectTransform.pivot;
        }

        return need;
    }


}
